//
//  AppDelegate.m
//  Doctors
//
//  Created by 王森 on 16/4/5.
//  Copyright © 2016年 王森. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginViewController.h"
#import "MassageTabBarViewController.h"
#import "LicensedTabBarViewController.h"
#import "JPUSHService.h"
#import <AudioToolbox/AudioToolbox.h>
#import "OrderDetailViewController.h"

@interface AppDelegate ()

@end



@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [WSNetworkApi updateBaseUrl:@"http://testartisan.91lds.com"];
    [WSNetworkApi BasePanth:@"/lds-artisan"];
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    [JPUSHService setupWithOption:launchOptions appKey:@"bd618b3e805e1c5d0994d428" channel:@"ios" apsForProduction:NO];
    
    
    
    
    [UIApplication sharedApplication].idleTimerDisabled = TRUE;
       
    NSString *classes=nil;
    
    
    if ([[[TMCache sharedCache]objectForKey:@"TeacherType" ] isEqualToString:@"1"]) {
        classes=@"MassageTabBarViewController";
    }
    else if ([[[TMCache sharedCache]objectForKey:@"TeacherType" ] isEqualToString:@"4"])
    {
        classes=@"LicensedTabBarViewController";
        
    }
    else
    {
        classes=@"LoginViewController";
        
    }
    
    
    Class class = NSClassFromString(classes);
    UIViewController *control = class.new;
    
    
    self.rootNav=[[UINavigationController alloc]initWithRootViewController:control];
    self.rootNav.navigationBar.hidden=YES;
    
    self.window.rootViewController = self.rootNav;
    
    [self.window makeKeyAndVisible];
    
    
    // Override point for customization after application launch.
    return YES;
}
#pragma mark - 实现单例方法
+ (AppDelegate *)shareInstance
{
    
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"收到通知:%@", [self logDic:userInfo]);
    self.userDic = [NSDictionary dictionaryWithDictionary:userInfo];
    
    completionHandler(UIBackgroundFetchResultNewData);
    
    //收到消息时，震动手机
    SystemSoundID soundID = kSystemSoundID_Vibrate;
    AudioServicesPlaySystemSound(soundID);
    
    
    //程序当前正处于前台
    if (application.applicationState == UIApplicationStateActive)
    {
        
        
        //播放声音
        AudioServicesPlaySystemSound(1007);//其中1007是系统声音的编号，其他的可用编号：
        
        [self showAlert];
        
    }
    
    else
    {
        
        [self showAlert];
        
    }
    
}


-(void)showAlert
{
    
    if ([ self.userDic[@"notifyType"] isEqualToString:@"3"]) {
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"您收到一条消息" message:@"您的订单被取消了" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        
    }
    else
    {
        NSString *content = [[ self.userDic valueForKey:@"aps"]objectForKey:@"alert"];
        //推送显示的内容
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"您收到一条消息" message:content delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        //是技师断
        if ([[[TMCache sharedCache]objectForKey:@"TeacherType" ] isEqualToString:@"4"]) {
            
            ALLOC(OrderDetailViewController, view);
            view.orderId = self.userDic[@"orderId"];
            //        view.orderId = @"94793";
            
            self.rootNav.navigationBar.hidden=NO;
            
            [self.rootNav pushViewController:view  animated:YES];
        }
        
    }
    
}
//、前台展示通知 Alert
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
    
    
}



- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
